package com.yyk.yiliao.ui.home.activity;

import android.content.Intent;
import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.yyk.yiliao.R;
import com.yyk.yiliao.base.BaseActivity;
import com.yyk.yiliao.base.BaseRecyclerAdapter;
import com.yyk.yiliao.base.BaseRecyclerHolder;
import com.yyk.yiliao.listener.ToolbarListenter;
import com.yyk.yiliao.ui.activity.detail.activity.Detail_Activity;
import com.yyk.yiliao.ui.activity.shopcart.ShopCart_Activity;
import com.yyk.yiliao.ui.gongyong.activity.WebViewActivity;
import com.yyk.yiliao.util.Md5Util2;
import com.yyk.yiliao.util.ToastUtil;
import com.yyk.yiliao.ui.login.activity.LogIn_Activity;
import com.yyk.yiliao.util.CheckDecimalPointUtil;
import com.yyk.yiliao.util.rx.ApiService;
import com.yyk.yiliao.util.rx.RxUtils;
import com.yyk.yiliao.bean.CartAddcart;
import com.yyk.yiliao.bean.OrderCartCountkey_Info;
import com.yyk.yiliao.bean.StoreGoodslist_Info;
import com.yyk.yiliao.widget.diver.CustomDecoration;
import com.yyk.yiliao.widget.paowuxian.BazierAnimView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 药房  商品列表
 */
public class PharmacyList_Activity extends BaseActivity {

    @BindView(R.id.rv_yao) //数据列表
            RecyclerView rvYao;
    @BindView(R.id.mPharmacyList_yf) // 头部药房 简介
            LinearLayout mPharmacyListYf;

    @BindView(R.id.mPharmacyLis_search)
    LinearLayout mPharmacyLisSearch;
Map<String, String> map;
    @BindView(R.id.b_picture)
    ImageView bPicture;
    @BindView(R.id.b_hospital_name)
    TextView bHospitalName;
    @BindView(R.id.rb_star)
    RatingBar rbStar;
    @BindView(R.id.tv_star)
    TextView tvStar;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.img_type)
    ImageView imgType;
    @BindView(R.id.img_invoice)
    ImageView imgInvoice;
    @BindView(R.id.img_isself)//到店自取
            ImageView imgIsself;
    @BindView(R.id.b_juli)
    TextView bJuli;
    @BindView(R.id.tv_one)
    TextView tvOne;
    @BindView(R.id.tv_two)
    TextView tvTwo;
    @BindView(R.id.tv_three)
    TextView tvThree;
    @BindView(R.id.tv_four)
    TextView tvFour;

    @BindView(R.id.tv_yaodianxiangqing)
    TextView tvYaodianxiangqing;


    //抛物线
    @BindView(R.id.cornerimg) //购物车图标
            ImageView cornerImg;
    @BindView(R.id.unread_msg_number)//购物车图标数量
            TextView msgNuber;
    @BindView(R.id.bezier_anim)
    BazierAnimView bazierAnimView;


    private List<StoreGoodslist_Info.DataBean> data = new ArrayList<>();
    private BaseRecyclerAdapter<StoreGoodslist_Info.DataBean> adapter;

    private String id; //  商品id ，跳转到商品详情
    private String beans; //传过来的bean
    private String name; //医院名字
    private int goodstypes;

    @Override
    public int getLayoutId() {
        return R.layout.activity_pharmacy_list;
    }

    @Override
    public void initView() {
        initToolbar();
    }

    private void initToolbar() {
        setBackArrow();
        setTitle(name);
        //分享按钮
        setMainTitleRightText(R.mipmap.icon_shangp_fx, new ToolbarListenter() {
            @Override
            public void onClickListenter() {

            }
        });
    }

    @Override
    public void initData() {
        initGetIntent();
        initPost();
        initAdapter();


    }

    private void initPost() {
        map = new TreeMap<>();

        map.put("id", id);
        map.put("page", "1");
        map.put("type", "");
        map.put("num", 1000 + "");

        map.put("sign", Md5Util2.createSign(map));
        setYao(map, true);
    }

    /**
     * 1.药品列表适配器
     */
    private void initAdapter() {
        adapter = new BaseRecyclerAdapter<StoreGoodslist_Info.DataBean>(PharmacyList_Activity.this, data, R.layout.adapter_item_pharmacylist) {
            @Override
            public void convert(final BaseRecyclerHolder holder, final StoreGoodslist_Info.DataBean item, int position, boolean isScrolling) {
                holder.setText(R.id.tv_name, item.getName());
                holder.setText(R.id.tv_address, item.getShopname());
                holder.setText(R.id.tv_describe, item.getDescribe());
                String money = CheckDecimalPointUtil.checkPoint(item.getMoney());
                holder.setText(R.id.tv_marketvalue, "¥" + money);
                int recipe = item.getRecipe();
                if (recipe == 1) {
                    holder.getView(R.id.tv_recipe).setVisibility(View.VISIBLE);
                } else {
                    holder.getView(R.id.tv_recipe).setVisibility(View.GONE);
                }
                holder.setText(R.id.tv_monthly, "销量" + item.getMonthly() + "件");
                holder.setImageByUrl(R.id.b_picture, ApiService.BASE_URL + item.getPic());
                holder.getView(R.id.iv_add).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int id = Hawk.get("uid", 0);
                        //判断 是否登陆 添加 购物车
                        if (id == 0) {
                            startAct(LogIn_Activity.class);
                        } else {
                            setBuyShop(item.getId(), item.getPic(), holder.getView(R.id.iv_add));
                        }
                    }
                });
            }
        };
        rvYao.addItemDecoration(new CustomDecoration(PharmacyList_Activity.this, CustomDecoration.VERTICAL_LIST, R.drawable.divider_white_ef_1px, 0));
        rvYao.setLayoutManager(new LinearLayoutManager(mActivity));
        rvYao.setAdapter(adapter);
        //如果子布局大小是固定的，起到优化的效果
        rvYao.setHasFixedSize(true);
        adapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView parent, View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putInt("id", data.get(position).getId());
                startAct(Detail_Activity.class, bundle);

//                EventBus.getDefault().postSticky(new MessageEvent(data.get(position).getId() + ""));
//                startAct(Detail_Activity.class);


            }
        });

    }


    private void initGetIntent() {

        if (getBundle() != null) {
            beans = getBundle().getString("bean");
            String[] split = beans.split(",");
            //id 是用来下面列表的
            id = split[0] + "";
            name = split[1];
            String pic = split[2];
            String address = split[3];
            //
            float star = Integer.parseInt(split[4]);
            int isself = Integer.parseInt(split[5]);
            int invoice = Integer.parseInt(split[6]);
            int type = Integer.parseInt(split[7]);
            //距离
            String distant = split[8];
            //1.
            bHospitalName.setText(name);
            //2.
            Glide.with(PharmacyList_Activity.this).load(ApiService.BASE_URL + pic).into(bPicture);//3.
            //3.
            tvAddress.setText(address);
            //4.
            rbStar.setRating(star / 2);
            tvStar.setText(star + "");
            if (isself == 1) {
                imgIsself.setVisibility(View.VISIBLE);

            } else {
                imgIsself.setVisibility(View.GONE);


            }
            //5.
            if (invoice == 1) {
                imgInvoice.setVisibility(View.VISIBLE);
            } else {
                imgInvoice.setVisibility(View.GONE);
            }

            //7.
            if (type == 1) {
                imgType.setVisibility(View.VISIBLE);
            } else {
                imgType.setVisibility(View.GONE);
            }
            //8.
            bJuli.setText(distant + "km");


        }
    }


    /**
     * 展示药品列表
     *
     * @param map
     */
    private void setYao(Map<String, String> map, final boolean flag) {
        RxUtils.getInstance().retrofit.create(ApiService.class).postStoreGoodslist(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<StoreGoodslist_Info>() {

                    @Override
                    public void onCompleted() {
                        //完成的时候调用

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();


                    }

                    @Override
                    public void onNext(StoreGoodslist_Info info) {
                        Logger.i("商品列表:" + info.toString());
                        if (info.getCode() == 1) {
                            rvYao.setVisibility(View.VISIBLE);
                            if (flag) {
                                data.clear();
                            }
                            //破几八名字
                            final List<StoreGoodslist_Info.DataBean> goodsList = info.getData();
                            if (goodsList.size() > 0 && goodsList != null) {
                                data.addAll(goodsList);
                            }
                            adapter.notifyDataSetChanged();
                        } else {
                            rvYao.setVisibility(View.GONE);
                        }
                    }

                });


    }

    @Override
    public void onResume() {
        super.onResume();
        //刷新购物车数量
        initShopNumber();
    }

    /**
     * 刷新购物车数量
     */
    public void reshefeshShopNumber(final ImageView buy, final String pic) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                bazierAnimView.startCartAnim(buy, cornerImg, R.layout.l_move, pic);
                initShopNumber();
            }
        });

    }

    /**
     * 购物车数量
     */
    private void initShopNumber() {
        Map<String, String> map = new TreeMap<>();
        map.put("uid", Hawk.get("uid", 0) + "");
        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postCarCountkey(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())
                .subscribe(new Subscriber<OrderCartCountkey_Info>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(OrderCartCountkey_Info info) {
                        Logger.w("购物车数量" + info.toString());
                        if (info.getCode() == 1) {
                            int dataNumber = info.getGoodstypes();
                            if (dataNumber == 0) {
                                msgNuber.setVisibility(View.INVISIBLE);
                            } else {
                                msgNuber.setText(dataNumber + "");
                                msgNuber.setVisibility(View.VISIBLE);

                            }

                        }
                    }
                });

    }

    /**
     * 添加购物车
     *
     * @param id
     */
    private void setBuyShop(int id, final String pic, final View view) {
        Map<String, String> map = new TreeMap<>();
        map.put("uid", Hawk.get("uid", 0) + "");
        map.put("gid", id + "");
        map.put("num", "1");
        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postCartAddcart(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<CartAddcart>() {

                    @Override
                    public void onCompleted() {
                        //完成的时候调用
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();

                    }

                    @Override
                    public void onNext(CartAddcart info) {
                        Logger.e("商品详情加入购物车" + info.getCode());
                        if (info.getCode() == 1) {
                            reshefeshShopNumber((ImageView) view, pic);
//                            ToastUtil.showShort(PharmacyList_Activity.this, "添加成功");
                        } else if (info.getCode() == 101) {
                            ToastUtil.showShort(PharmacyList_Activity.this, "没有该商品 ");
                        } else if (info.getCode() == 102) {
                            ToastUtil.showShort(PharmacyList_Activity.this, "插入失败 ");
                        } else if (info.getCode() == 103) {
                            ToastUtil.showShort(PharmacyList_Activity.this, "购物车已存在 ");
                        } else if (info.getCode() == 104) {
                            ToastUtil.showShort(PharmacyList_Activity.this, "商品数量修改失败 ");
                        } else {
                            ToastUtil.showShort(PharmacyList_Activity.this, "商品删除失败 ");
                        }

                    }


                });
    }

    private void hideColor() {
        tvOne.setTextColor(0xff202020);
        tvTwo.setTextColor(0xff202020);
        tvThree.setTextColor(0xff202020);
        tvFour.setTextColor(0xff202020);
    }

    /**
     * 1. 购物车悬浮控件  突然有一个大胆的想法，自定义继承 重写点击事件 判断是否 账号登陆
     * 2.药店详情
     * 3. 搜索    暂无
     * 4.头部 大药店
     * 5. 全部药品
     * 6.处方药
     * 7.非处方药
     * 8.其他商品
     *
     * @param view
     */
    @OnClick({R.id.cornerimg, R.id.tv_yaodianxiangqing, R.id.mPharmacyLis_search, R.id.mPharmacyList_yf, R.id.tv_one, R.id.tv_two, R.id.tv_three, R.id.tv_four})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.cornerimg:
                int uid = Hawk.get("uid", 0);
                Logger.i("账号id==" + uid);
                if (uid == 0) {
                    Intent intent2 = new Intent(PharmacyList_Activity.this, LogIn_Activity.class);
                    startActivity(intent2);
                } else {
                    Intent intent2 = new Intent(PharmacyList_Activity.this, ShopCart_Activity.class);
                    startActivity(intent2);
                }
                break;

            case R.id.tv_yaodianxiangqing:
                Intent tv_yaodianxiangqing = new Intent();
                tv_yaodianxiangqing.putExtra("toolbar_tv", name);
                tv_yaodianxiangqing.putExtra("url", ApiService.H5_URL_HARMACY + "&drugstoreId=" + id);
                startAct(tv_yaodianxiangqing, WebViewActivity.class, null);
                break;

            case R.id.mPharmacyLis_search:
                break;
            case R.id.mPharmacyList_yf:
                Intent mPharmacyList_yf = new Intent();
                mPharmacyList_yf.putExtra("toolbar_tv", name);
                mPharmacyList_yf.putExtra("url", ApiService.H5_URL_HARMACY + "&drugstoreId=" + id);
                startAct(mPharmacyList_yf, WebViewActivity.class, null);
                break;
            case R.id.tv_one:
                hideColor();
                tvOne.setTextColor(getResources().getColor(R.color.blue_00));
                Map<String, String> map = new TreeMap<>();
                map.put("page", "1");
                map.put("id", id);
                map.put("type", "");
                map.put("num", 1000 + "");
                map.put("sign", Md5Util2.createSign(map));
                setYao(map, true);

                break;
            case R.id.tv_two:
                hideColor();
                tvTwo.setTextColor(getResources().getColor(R.color.blue_00));
                Map<String, String> map2 = new TreeMap<>();
                map2.put("page", "1");
                map2.put("type", 1 + "");
                map2.put("id", id);
                map2.put("num", 1000 + "");

                map2.put("sign", Md5Util2.createSign(map2));
                setYao(map2, true);
                break;
            case R.id.tv_three:
                hideColor();
                tvThree.setTextColor(getResources().getColor(R.color.blue_00));
                Map<String, String> map3 = new TreeMap<>();
                map3.put("page", "1");
                map3.put("type", 0 + "");
                map3.put("id", id);
                map3.put("num", 1000 + "");
                map3.put("sign", Md5Util2.createSign(map3));
                setYao(map3, true);
                break;
            case R.id.tv_four:
                hideColor();
                tvFour.setTextColor(getResources().getColor(R.color.blue_00));
                Map<String, String> map4 = new TreeMap<>();
                map4.put("page", "1");
                map4.put("type", 2 + "");
                map4.put("id", id);
                map4.put("num", 1000 + "");

                map4.put("sign", Md5Util2.createSign(map4));
                setYao(map4, true);
                break;
        }

    }


}
